package com.example.demo.controller;

import com.example.demo.dao.AiAgentDao;
import com.example.demo.dao.AgentConversationDao;
import com.example.demo.dao.AgentMessageDao;
import com.example.demo.entity.pojo.AiAgent;
import com.example.demo.entity.pojo.AgentConversation;
import com.example.demo.entity.pojo.AgentMessage;
import com.example.demo.entity.dto.TokenUserDto;
import com.example.demo.entity.vo.ResponseVO;
//import com.example.demo.service.QianwenService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * AI Agent管理控制器
 */
@RestController
@RequestMapping("/agent")
public class AiAgentController extends BaseController {

    @Autowired
    private AiAgentDao aiAgentDao;

    @Autowired
    private AgentConversationDao agentConversationDao;

    @Autowired
    private AgentMessageDao agentMessageDao;

    //@Autowired
    //private QianwenService qianwenService;

    /**
     * 获取可访问的Agent列表
     * 
     * @param request HTTP请求对象，用于获取用户token
     * @return 响应结果，包含Agent列表
     */
    @GetMapping("/getAccessibleAgents")
    public ResponseVO<List<AiAgent>> getAccessibleAgents(HttpServletRequest request) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 查询用户可访问的Agent列表
            List<AiAgent> agents = aiAgentDao.queryAccessibleAgents(tokenUserDto.getUserId());

            return getSuccess("获取Agent列表成功！", agents);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 获取我创建的Agent列表
     * 
     * @param request HTTP请求对象，用于获取用户token
     * @return 响应结果，包含Agent列表
     */
    @GetMapping("/getMyAgents")
    public ResponseVO<List<AiAgent>> getMyAgents(HttpServletRequest request) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 查询用户创建的Agent列表
            List<AiAgent> agents = aiAgentDao.queryByCreatorId(tokenUserDto.getUserId());

            return getSuccess("获取我的Agent列表成功！", agents);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 创建新的Agent
     * 
     * @param request HTTP请求对象，用于获取用户token
     * @param agentName Agent名称
     * @param agentDescription Agent描述
     * @param systemPrompt 系统提示词
     * @param isPublic 是否公开
     * @return 响应结果
     */
    @PostMapping("/createAgent")
    public ResponseVO<AiAgent> createAgent(HttpServletRequest request,
                                         @RequestParam String agentName,
                                         @RequestParam String agentDescription,
                                         @RequestParam String systemPrompt,
                                         @RequestParam(defaultValue = "0") Integer isPublic) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 参数验证
            if (StringUtils.isBlank(agentName)) {
                return getFail("Agent名称不能为空！");
            }
            if (StringUtils.isBlank(systemPrompt)) {
                return getFail("系统提示词不能为空！");
            }

            // 创建Agent对象
            AiAgent agent = new AiAgent();
            agent.setAgentName(agentName.trim());
            agent.setAgentDescription(agentDescription);
            agent.setCreatorId(tokenUserDto.getUserId());
            agent.setModelProvider("qianwen");
            agent.setModelName("qwen-turbo");
            agent.setSystemPrompt(systemPrompt);
            agent.setTemperature(new java.math.BigDecimal("0.7"));
            agent.setMaxTokens(2000);
            agent.setIsPublic(isPublic);
            agent.setStatus(1);

            // 保存到数据库
            int result = aiAgentDao.insert(agent);
            if (result > 0) {
                return getSuccess("创建Agent成功！", agent);
            } else {
                return getFail("创建Agent失败！");
            }

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 开始与Agent对话
     * 
     * @param request HTTP请求对象，用于获取用户token
     * @param agentId Agent ID
     * @return 响应结果，包含会话信息
     */
    @PostMapping("/startConversation")
    public ResponseVO<AgentConversation> startConversation(HttpServletRequest request,
                                                         @RequestParam Integer agentId) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 参数验证
            if (agentId == null) {
                return getFail("Agent ID不能为空！");
            }

            // 查询Agent信息
            AiAgent agent = aiAgentDao.queryById(agentId);
            if (agent == null) {
                return getFail("Agent不存在！");
            }

            // 检查访问权限
            if (agent.getIsPublic() == 0 && !agent.getCreatorId().equals(tokenUserDto.getUserId())) {
                return getFail("您没有权限访问该Agent！");
            }

            // 创建新会话
            AgentConversation conversation = new AgentConversation();
            conversation.setAgentId(agentId);
            conversation.setUserId(tokenUserDto.getUserId());
            conversation.setConversationTitle("与" + agent.getAgentName() + "的对话");
            conversation.setSessionId(UUID.randomUUID().toString());
            conversation.setStatus(1);

            // 保存会话
            int result = agentConversationDao.insert(conversation);
            if (result > 0) {
                return getSuccess("开始对话成功！", conversation);
            } else {
                return getFail("创建会话失败！");
            }

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 发送消息给Agent
     *
     * @param request HTTP请求对象，用于获取用户token
     * @param sessionId 会话ID
     * @param message 用户消息
     * @return 响应结果，包含Agent回复
     */
    @PostMapping("/sendMessage")
    public ResponseVO<AgentMessage> sendMessage(HttpServletRequest request,
                                              @RequestParam String sessionId,
                                              @RequestParam String message) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 参数验证
            if (StringUtils.isBlank(sessionId)) {
                return getFail("会话ID不能为空！");
            }
            if (StringUtils.isBlank(message)) {
                return getFail("消息内容不能为空！");
            }

            // 查询会话信息
            AgentConversation conversation = agentConversationDao.queryBySessionId(sessionId);
            if (conversation == null) {
                return getFail("会话不存在！");
            }

            // 验证会话权限
            if (!conversation.getUserId().equals(tokenUserDto.getUserId())) {
                return getFail("您没有权限访问该会话！");
            }

            // 查询Agent信息
            AiAgent agent = aiAgentDao.queryById(conversation.getAgentId());
            if (agent == null) {
                return getFail("Agent不存在！");
            }

            // 保存用户消息
            AgentMessage userMessage = new AgentMessage();
            userMessage.setConversationId(conversation.getId());
            userMessage.setMessageType("user");
            userMessage.setContent(message);
            agentMessageDao.insert(userMessage);

            // 调用千问API获取回复
            //String agentReply = qianwenService.chat(agent.getSystemPrompt(), message, sessionId);

            // 保存Agent回复
            AgentMessage agentMessage = new AgentMessage();
            agentMessage.setConversationId(conversation.getId());
            agentMessage.setMessageType("assistant");
            //agentMessage.setContent(agentReply);
            agentMessage.setModelInfo("{\"provider\":\"" + agent.getModelProvider() +
                                    "\",\"model\":\"" + agent.getModelName() + "\"}");
            agentMessageDao.insert(agentMessage);

            // 更新会话时间
            conversation.setUpdateTime(new Date());
            agentConversationDao.update(conversation);

            return getSuccess("发送消息成功！", agentMessage);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 获取会话历史消息
     *
     * @param request HTTP请求对象，用于获取用户token
     * @param sessionId 会话ID
     * @param limit 限制数量
     * @return 响应结果，包含消息列表
     */
    @GetMapping("/getConversationHistory")
    public ResponseVO<List<AgentMessage>> getConversationHistory(HttpServletRequest request,
                                                               @RequestParam String sessionId,
                                                               @RequestParam(defaultValue = "50") Integer limit) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 参数验证
            if (StringUtils.isBlank(sessionId)) {
                return getFail("会话ID不能为空！");
            }

            // 查询会话信息
            AgentConversation conversation = agentConversationDao.queryBySessionId(sessionId);
            if (conversation == null) {
                return getFail("会话不存在！");
            }

            // 验证会话权限
            if (!conversation.getUserId().equals(tokenUserDto.getUserId())) {
                return getFail("您没有权限访问该会话！");
            }

            // 查询消息历史
            List<AgentMessage> messages = agentMessageDao.queryByConversationId(conversation.getId(), limit);

            return getSuccess("获取会话历史成功！", messages);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 获取用户的会话列表
     *
     * @param request HTTP请求对象，用于获取用户token
     * @param limit 限制数量
     * @return 响应结果，包含会话列表
     */
    @GetMapping("/getMyConversations")
    public ResponseVO<List<AgentConversation>> getMyConversations(HttpServletRequest request,
                                                                @RequestParam(defaultValue = "20") Integer limit) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 查询用户的会话列表
            List<AgentConversation> conversations = agentConversationDao.queryByUserId(tokenUserDto.getUserId(), limit);

            return getSuccess("获取会话列表成功！", conversations);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }
}
